package com.older.wptsb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.older.wptsb.domain.dto.UserElderRelDTO;
import com.older.wptsb.domain.po.*;
import com.older.wptsb.domain.vo.AlertLogVO;
import com.older.wptsb.domain.vo.ElderVO;
import com.older.wptsb.domain.vo.HealthDataVO;
import com.older.wptsb.mapper.AlertLogMapper;
import com.older.wptsb.mapper.FamilyElderMapper;
import com.older.wptsb.mapper.UserElderRelMapper;
import com.older.wptsb.mapper.UserMapper;
import com.older.wptsb.service.FamilyElderService;
import com.older.wptsb.util.UserContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class FamilyElderServiceImpl extends ServiceImpl<FamilyElderMapper, Elder> implements FamilyElderService {

    @Resource
    private FamilyElderMapper familyElderMapper;
    @Resource
    private UserElderRelMapper userElderRelMapper;
    @Resource
    private AlertLogMapper alertLogMapper;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Override
    public List<HealthDataVO> getElderHealthData() {
        Long currentUserId = UserContext.getUserId();

        // 从关联关系表中获取用户关联的所有老人ID
        List<UserElderRel> userElderRels = userElderRelMapper.selectList(
                new QueryWrapper<UserElderRel>().eq("user_id", currentUserId)
        );

        if (userElderRels != null && !userElderRels.isEmpty()) {
            List<HealthDataVO> healthDataList = new ArrayList<>();

            // 遍历所有关联的老人
            for (UserElderRel rel : userElderRels) {
                String elderId = rel.getElderId();

                // 从Redis中获取该老人的最新健康数据
                String redisKey = "health_data:" + elderId;
                List<Object> rawDataList = redisTemplate.opsForList().range(redisKey, 0, 0); // 获取最新的一个数据

                if (rawDataList != null && !rawDataList.isEmpty()) {
                    Object obj = rawDataList.get(0);
                    if (obj instanceof HealthData) {
                        HealthData healthData = (HealthData) obj;
                        // 转换为HealthDataVO对象
                        HealthDataVO vo = HealthDataVO.builder()
                                .dataId(healthData.getDataId())
                                .elderId(healthData.getElderId())
                                .communityId(healthData.getCommunityId())
                                .elderName(healthData.getElderName())
                                .heartRate(healthData.getHeartRate())
                                .bloodOxygen(healthData.getBloodOxygen())
                                .bloodPressure(healthData.getBloodPressure())
                                .sleepQuality(healthData.getSleepQuality())
                                .createTime(healthData.getCreateTime())
                                .location(healthData.getLocation())
                                .build();
                        healthDataList.add(vo);
                    }
                }
            }

            // 如果从Redis中获取到了数据，则返回
            if (!healthDataList.isEmpty()) {
                return healthDataList;
            }
        }

        // 如果Redis中没有数据，则从数据库获取
        return familyElderMapper.selectElderHealthData(currentUserId);
    }

    @Override
    public void bindElder(UserElderRelDTO userElderRelDTO) {
        Long currentUserId = UserContext.getUserId();
        System.out.println(userElderRelDTO);
        // 根据老人姓名查找老人信息
        Elder elder = this.getOne(new QueryWrapper<Elder>().eq("name", userElderRelDTO.getElderName()));
        System.out.println( elder);
        if (elder == null) {
            throw new RuntimeException("未找到指定的老人信息");
        }

        // 创建用户与老人的关联关系
        UserElderRel userElderRel = new UserElderRel();
        userElderRel.setUserId(String.valueOf(currentUserId));
        userElderRel.setElderId(String.valueOf(elder.getElderId()));

        // 设置创建时间
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        userElderRel.setCreateTime(now.format(formatter));

        userElderRelMapper.insert(userElderRel);
    }

    @Override
    public List<AlertLogVO> alertElder() {
        Long currentUserId = UserContext.getUserId();

        // 查询当前用户关联的所有老人
        List<UserElderRel> userElderRels = userElderRelMapper.selectList(
                new QueryWrapper<UserElderRel>().eq("user_id", currentUserId)
        );

        List<AlertLogVO> alertLogs = new ArrayList<>();

        if (userElderRels != null && !userElderRels.isEmpty()) {
            // 提取所有关联的老人ID
            List<String> elderIds = userElderRels.stream()
                    .map(UserElderRel::getElderId)
                    .collect(Collectors.toList());

            // 查询这些老人的预警信息
            List<AlertLog> alertLogList = alertLogMapper.selectList(
                    new QueryWrapper<AlertLog>().in("elder_id", elderIds)
            );

            // 转换为VO对象
            for (AlertLog alertLog : alertLogList) {
                AlertLogVO vo = new AlertLogVO();
                vo.setAlertId(alertLog.getAlertId());
                vo.setElderId(alertLog.getElderId());
                vo.setElderName(alertLog.getElderName());
                vo.setAlertType(alertLog.getAlertType());
                vo.setAlertLevel(alertLog.getAlertLevel());
                vo.setLocation(alertLog.getLocation());
                vo.setStatus(alertLog.getStatus());
                vo.setCreateTime(alertLog.getCreateTime());
                vo.setResolveTime(alertLog.getResolveTime());
                alertLogs.add(vo);
            }
        }
        return alertLogs;
    }

    @Override
    public List<ElderVO> getElderList() {
        Long currentUserId = UserContext.getUserId();

        // 查询当前用户关联的所有老人
        List<UserElderRel> userElderRels = userElderRelMapper.selectList(
                new QueryWrapper<UserElderRel>().eq("user_id", currentUserId)
        );

        List<ElderVO> elderList = new ArrayList<>();

        if (userElderRels != null && !userElderRels.isEmpty()) {
            // 提取所有关联的老人ID
            List<String> elderIds = userElderRels.stream()
                    .map(UserElderRel::getElderId)
                    .collect(Collectors.toList());

            // 查询这些老人的信息
            List<Elder> elders = this.list(new QueryWrapper<Elder>().in("elder_id", elderIds));

            // 转换为VO对象
            for (Elder elder : elders) {
                ElderVO vo = ElderVO.builder()
                        .elderId(elder.getElderId())
                        .name(elder.getName())
                        .gender(elder.getGender())
                        .age(elder.getAge())
                        .idCard(elder.getIdCard())
                        .communityId(elder.getCommunityId())
                        .address(elder.getAddress())
                        .healthSummary(elder.getHealthSummary())
                        .status(elder.getStatus())
                        .emergencyContacts(elder.getEmergencyContacts())
                        .emergencyPhone(elder.getEmergencyPhone())
                        .build();
                elderList.add(vo);
            }
        }
        return elderList;
    }

    @Override
    public List<HealthDataVO> getElderHealthData(String elderId) {
        // 查询指定老人的所有健康数据
        return familyElderMapper.selectElderHealthDataByElderId(elderId);
    }

}
